package com.sgcc.ln.pmos.e_ln_home.activity;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.ln.pmos.arouter.common.CommonArouterPath;
import com.sgcc.ln.pmos.arouter.home.HomeArouterPath;
import com.sgcc.ln.pmos.common.base.BaseActivity;
import com.sgcc.ln.pmos.common.http.DownloadUtil;
import com.sgcc.ln.pmos.common.http.HttpRequestUtils;
import com.sgcc.ln.pmos.common.utils.DateUtils;
import com.sgcc.ln.pmos.common.utils.FileUtils;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.ln.pmos.e_ln_home.adapter.FileListAdapter;
import com.sgcc.ln.pmos.e_ln_home.bean.FileBean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.Response;

/**
 * 信息披露内容
 */
@Route(path = HomeArouterPath.HOME_INFOMATIONCONTENT)
public class InfomationContentActivity extends BaseActivity {

    private TitleBar mTitleBar;
    private TextView mTvTitle;
    private TextView mTvTime;
    private TextView mTvRange;
    private TextView mTvNumber;
    private WebView mWvContent;
    private RecyclerView mRvFile;
    private String mTitle, mOperateDate, mPublishType, mContent, mAttachment, mReadAmount;
    private FileListAdapter mFileListAdapter;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_infomationcontent;
    }

    @Override
    protected void initViews() {
        super.initViews();


        mTitle = getIntent().getStringExtra("title");
        mOperateDate = getIntent().getStringExtra("operateDate");
        mPublishType = getIntent().getStringExtra("publishType");
        mContent = getIntent().getStringExtra("content");
        mAttachment = getIntent().getStringExtra("attachment");
        mReadAmount = getIntent().getStringExtra("readAmount");


        findViewByIds();
    }

    private void findViewByIds() {
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvTime = (TextView) findViewById(R.id.tv_time);
        mTvRange = (TextView) findViewById(R.id.tv_range);
        mTvNumber = (TextView) findViewById(R.id.tv_number);
        mWvContent = (WebView) findViewById(R.id.wv_content);
        mRvFile = (RecyclerView) findViewById(R.id.rv_file);

        mTitleBar.setTitle("信息展示");
        mTvTitle.setText(mTitle);

        String time = "";
        try {
            time = StringUtils.isEmpty(DateUtils.getStrng_to_Times_ymdhms1(mOperateDate)) ?
                    DateUtils.get_TimesYMDHMSG1(mOperateDate) :
                    DateUtils.getStrng_to_Times_ymdhms1(mOperateDate);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        mTvTime.setText(time);
        mTvRange.setText(mPublishType);
        mTvNumber.setText(mReadAmount);

        if (TextUtils.isEmpty(mContent)) {
            mWvContent.setVisibility(View.GONE);
        } else {
            mWvContent.setVisibility(View.VISIBLE);
            WebSettings settings = mWvContent.getSettings();
            settings.setDefaultTextEncodingName("utf-8");
            mWvContent.loadDataWithBaseURL(null, mContent, "text/html", "utf-8", null);
        }


        if (!TextUtils.isEmpty(mAttachment)) {
            Gson gson = new Gson();
            Type type = new TypeToken<List<FileBean>>() {
            }.getType();
            List<FileBean> list = gson.fromJson(mAttachment, type);

            LinearLayoutManager secondLLManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
            mRvFile.setLayoutManager(secondLLManager);
            mRvFile.setItemAnimator(new DefaultItemAnimator());
            mFileListAdapter = new FileListAdapter(this);
            mFileListAdapter.setOnItemClickListener(new FileListAdapter.OnItemClickListener() {
                @Override
                public void itemClickListener(int position, FileBean bean) {
                    if ("pdf".toLowerCase().equals(bean.getFileType().toLowerCase())) {
                        openSystemFile(bean.getId());
                    } else {
                        ToastUtils.showShort("该文件不支持预览");
                    }
                }
            });
            mRvFile.setAdapter(mFileListAdapter);
            mFileListAdapter.addData(list);
        }
    }

    /**
     * 下载并调用系统方式打开文件
     *
     * @param fileId
     */
    public void openSystemFile(String fileId) {
        showLoading();
        String webUrl = "https://pmos.ln.sgcc.com.cn/px-settlement-infpubmeex/fileService/preview?fileId=" + fileId + "#toolbar=0";
        DownloadUtil.get().downloadGET(mContext, webUrl,
                mContext.getExternalFilesDir("pdf"),
                new DownloadUtil.OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file) {
                        dismissLoading();
                        String fileType = getFileExtension(file);
                        if ("pdf".toLowerCase().equals(fileType.toLowerCase())) {
                            ARouter.getInstance()
                                    .build(CommonArouterPath.COMMON_PDFPREVIEW)
                                    .withString("mFilePath", file.getPath())
                                    .navigation();
                        } else {
                            FileUtils.openFileByPath(mContext, file.getPath());
                        }
                    }

                    @Override
                    public void onDownloading(int progress) {
                    }

                    @Override
                    public void onDownloadFailed(Exception e) {
                        dismissLoading();
                        ToastUtils.showShort("文件加载失败");
                    }
                });
    }

    /**
     * 获取文件扩展名
     *
     * @param file
     * @return
     */
    private String getFileExtension(File file) {
        String fileName = file.getName();
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        else return "";
    }


}
